package cn.com.connext.scrm.utils.wechat;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.TmpMsgRecord;
import cn.com.connext.scrm.service.WxAPIService;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.TmpMsgRecordService;
import cn.com.connext.scrm.utils.HttpUtils;
import cn.com.connext.scrm.web.rest.vm.Template;
import cn.com.connext.scrm.web.rest.vm.TemplateParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @Description:
 * @author: ZHaoYul
 * @date: 2021/8/23 11:02
 */
@Component
public class WxMessageSend {
    private final static Logger log = LoggerFactory.getLogger(WxMessageSend.class);
    @Autowired
    private WxAPIService wxAPIService;
    @Autowired
    private TmpMsgRecordService tmpMsgRecordService;

    /**
     * 下发微信订阅消息
     * @param backUrl 回调url
     * @param templateId 模板id
     * @param openId 用户id
     * @param paras 模板参数
     */
    public JsonResult sendMessageWx(String backUrl, String templateId, String openId, List<TemplateParam> paras, TmpMsgRecord tmpMsgRecord){
        JsonResult result = new JsonResult();
        String Access_Token = wxAPIService.getThisAccessToken();
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
        Template template = new Template();
        //模板id
        template.setTemplate_id(templateId);
        template.setTouser(openId);
        template.setMiniprogram_state(Constants.MINIPROGRAM_STATE);
        //回调路径
        if (StringUtils.isNotBlank(backUrl)) {
            template.setPage(backUrl);
        }

//        List<TemplateParam> paras = new ArrayList<TemplateParam>();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
//        String expireTime = sdf.format(new Date());
//        paras.add(new TemplateParam("thing1", "阿龍測試發送"));
//        paras.add(new TemplateParam("time2", expireTime));
//        paras.add(new TemplateParam("thing3", "您有一份礼遇即将到期，点击可查看详情"));
        template.setTemplateParamList(paras);
        requestUrl=requestUrl.replace("ACCESS_TOKEN", Access_Token);

        log.info("开始调用微信接口发送消息",requestUrl,JSON.toJSONString(template));
        String resultString = HttpUtils.doPost(requestUrl, template.toJSON());
        JSONObject jsonResult = JSONObject.parseObject(resultString);
        if (jsonResult != null) {
            System.out.println(jsonResult);
            int errorCode = jsonResult.getInteger("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                log.info("消息发送成功");
                log.info(String.format("%s %s %s %s",backUrl,templateId,openId,paras));
                if (null != tmpMsgRecord) {
                    tmpMsgRecordService.add(tmpMsgRecord);
                    log.info("订阅消息recordMsg保存:{}", JSON.toJSONString(tmpMsgRecord));
                }
                result.setMessage("Send Success");
                result.setState(0);
            } else {
                log.info("订阅消息发送失败 errorCode:{},errorMessage:{}", errorCode,errorMessage);
                result.setMessage("订阅消息发送失败:" + errorCode + "," + errorMessage);
                result.setState(1);
            }
        } else {
            result.setMessage("订阅消息发送失败:jsonResult为空");
            result.setState(1);
        }
        return result;
    }

//    public static void main(String[] args) {
//
//
//        RestTemplate restTemplate=new RestTemplate();
////        String Access_Token = wxAPIService.getThisAccessToken();
//        String requestUrl1 = Constants.GetAccessTokenUrl.replace("APPID", Constants.APPID).replace("APPSECRET", Constants.SECRET);
////        log.info(" start request URL = {} ", requestUrl);
//        JSONObject result=restTemplate.getForEntity(requestUrl1, JSONObject.class).getBody();
//        String accessToken=result.getString("access_token");
//        System.out.println(accessToken);
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//        Template template = new Template();
//        //模板id
//        template.setTemplate_id("YeTyVmJiVPlLCWRq1EzFQIuFZUJC6oeqN_kX5dHu7r8");
//        template.setTouser("oMysc5EZbnTcmf-YqM8eB3L-LYQo");
//        template.setPage("page/reward/enterPrize/index?activityId=ScanCodeCollectCoupons");
//        List<TemplateParam> paras = new ArrayList<TemplateParam>();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
//        String expireTime = sdf.format(new Date());
//        paras.add(new TemplateParam("thing1", "阿龍測試發送"));
//
//        paras.add(new TemplateParam("time2", expireTime));
//        paras.add(new TemplateParam("thing3", "您有一份礼遇即将到期，点击可查看详情"));
//        template.setTemplateParamList(paras);
//        requestUrl=requestUrl.replace("ACCESS_TOKEN", accessToken);
//        String resultString = HttpUtils.doPost(requestUrl, template.toJSON());
//        JSONObject jsonResult = JSONObject.parseObject(resultString);
//        System.out.println(resultString);
//        System.out.println(jsonResult);
//        System.out.println(JSON.toJSONString(jsonResult));
//    }
}
